package com.lijian.study.mybatisplus.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * <p>ProjectName: mybatisplus</p>
 * <p>FullClassname: com.lijian.study.mybatisplus.config.MybatisConfig</p>
 * <p>Date: 2024/11/14 18:45</p>
 * <p>Description: </p>
 *
 * @author jianli
 * @version 1.0
 */
@Configuration
public class MybatisConfig {

	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		// 分页插件
		interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
		// 防止全表更新与删除插件
		interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
		return interceptor;
	}


	// 设置自动填充策略

	/**
	 * 如果已经在字段上设置了@TableField(fill = FieldFill.INSERT) 或 @TableField(fill = FieldFill.INSERT_UPDATE)
	 * 该方法是多余的
	 *
	 * @return mybatis-plus对空字段类型的处理
	 */
	@Bean
	public MetaObjectHandler myMetaObjectHandler() {
		return new MetaObjectHandler() {
			@Override
			public void insertFill(MetaObject metaObject) {
				Object created = getFieldValByName("created", metaObject);
				if (null == created) {
					//字段为空，可以进行填充
					setFieldValByName("created", LocalDateTime.now(), metaObject);
				}

				Object updated = getFieldValByName("updated", metaObject);
				if (null == updated) {
					//字段为空，可以进行填充
					setFieldValByName("updated", LocalDateTime.now(), metaObject);
				}
			}

			@Override
			public void updateFill(MetaObject metaObject) {
				//更新数据时，直接更新字段
				setFieldValByName("updated", LocalDateTime.now(), metaObject);
			}
		};
	}


}
